import type { ReactNode } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '@store/AuthProvider'
import { ROUTES } from './paths'
import LoadingOverlay from '@components/LoadingOverlay'

type ProtectedRouteProps = {
  children: ReactNode
}

const ProtectedRoute = ({ children }: ProtectedRouteProps) => {
  const location = useLocation()
  const { user, loading } = useAuth()

  if (loading) {
    return <LoadingOverlay message="加载用户信息..." />
  }

  if (!user) {
    return (
      <Navigate
        to={ROUTES.login}
        replace
        state={{ from: location.pathname + location.search }}
      />
    )
  }

  return <>{children}</>
}

export default ProtectedRoute


